﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FRW.Common.Configuration;

namespace Money.Plugins.Import.RbsImport
{
    public class Configuration : IConfiguration
    {
        // TODO tidy up transaction number handling
        private long _id;
        private int _fieldCount;

        public long Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public long GetNewId()
        {
            _id++;

            return _id;
        }

        public String CurrentTransactionNo
        {
            get
            {
                return _id.ToString("D8");
            }
        }

        public int FieldCount
        {
            get { return _fieldCount; }
            set { _fieldCount = value; }
        }

        public List<TransactionMatch> Categories { get; set ;}
        public string MatchString { get; set; }
        public bool ApplyNameTidy { get; set; }

        public Configuration()
        {
        }

        public void DefaultConfiguration()
        {
            _fieldCount = 8;
            MatchString = "^(?<date>[0-9]+/[0-9]+/[0-9]+),(?<type>.*?),\"'(?<desc>.*?)\",(?<amount>.*?),(?<balance>.*?),\"'(?<accountName>.*?)\",\"'(?<accountNo>.*?)\"";
            ApplyNameTidy = true;
            Categories = new List<TransactionMatch>();
        }

        public void CheckConfiguration()
        {
            List<TransactionMatch> removeList = new List<TransactionMatch>();

            // Lets check that none of the categories have been deleted, if so we need to remove our mapping
            foreach (TransactionMatch mapping in Categories)
            {
                if (Money.Categories.CategoryList != null)
                {
                    string categoryName = Money.Categories.CategoryList.GetCategoryName(Convert.ToInt32(mapping.CategoryId));

                    if (String.IsNullOrWhiteSpace(categoryName) || categoryName.Equals("Unknown", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // delete the mapping as it cannot point to a category that no longer exists
                        removeList.Add(mapping);
                    }
                }
            }

            foreach (TransactionMatch mapping in removeList)
            {
                Categories.Remove(mapping);
            }
        }
    }
}
